package com.easy.util;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class InnerCaptchaUtil {
    //计时Map 用户存储验证码 有效时间单位为秒
    public static final ExpiringMap<String,String> captchaMap=new ExpiringMap<>(5*60*1000);

    public static final LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100,4,5);

    /**
     * 获取验证码的方法
     * @return
     */
    public static Map getCaptcha(){
        Map<String,String> result=new HashMap<>();
        String key= UUID.randomUUID().toString();
        lineCaptcha.createCode();
        //验证码
        String code=lineCaptcha.getCode();
        //验证码图片base64
        String base=lineCaptcha.getImageBase64();
        result.put("key",key);
        result.put("base","data:image/png;base64,"+base);
        captchaMap.put(key,code);
        return result;
    }

    /**
     * 验证码验证方法
     * @param key
     * @param code
     * @return
     */
    public static boolean verifyCaptcha(String key,String code){
        System.out.println( key);
        System.out.println( code);
        boolean hasKey=captchaMap.containsKey(key);
        System.out.println( hasKey);
        if(hasKey){
            String captcha=captchaMap.get(key);
            System.out.println( captcha);
            if(captcha.equalsIgnoreCase(code)){
                captchaMap.remove(key);
                return true;
            }
        }
        return false;
    }
}
